package Test;
import java.io.*;
import java.math.*;
import java.security.*;
import java.security.spec.*;
import java.util.Random;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;

public class KeyAgree{
    public static void main(String args[ ]) throws Exception{
        // 读取对方的DH公钥
        FileInputStream f1=new FileInputStream("PubKeyB.txt");
        ObjectInputStream b1=new ObjectInputStream(f1);
        PublicKey  pbk=(PublicKey)b1.readObject( );
        //读取自己的DH私钥
        FileInputStream f2=new FileInputStream("PriKeyA.txt");
        ObjectInputStream b2=new ObjectInputStream(f2);
        PrivateKey  prk=(PrivateKey)b2.readObject( );
        // 执行密钥协定
        KeyAgreement ka=KeyAgreement.getInstance("DH");
        ka.init(prk);
        ka.doPhase(pbk,true);
        //生成共享信息
        byte[ ] sb=ka.generateSecret();
        for(int i=0;i<sb.length;i++){
            System.out.printf(sb[i]+",");
            if((i+1)%10==0){
                System.out.printf("\n");
            }
        }
        Random rand = new Random();
        SecretKeySpec k=new  SecretKeySpec(sb,0,24,"DESede");
        FileOutputStream  f=new FileOutputStream("key1.dat");
        ObjectOutputStream b=new  ObjectOutputStream(f);
        b.writeObject(k);
        FileInputStream f0=new FileInputStream("key1.dat");
        ObjectInputStream b0=new ObjectInputStream(f0);
        Key k0=(Key)b0.readObject( );
        byte[ ] kb=k0.getEncoded( );
        FileOutputStream  f3=new FileOutputStream("keykb1.dat");
        f3.write(kb);
    }
}
